﻿using AutoMapper;
using MediatR;
using SU.Center.Domain.RBAC;
using SU.Center.Infa;
using System.Transactions;

namespace SU.Center.Api.Handler.RBAC
{
    /// <summary>
    /// 新增用户信息(事务)
    /// </summary>
    public class InserUserInfoHandler : IRequestHandler<InserUserInfoRepsultDto, ApiResult>
    {
        private readonly IBaseReposiotry<UserInfo> _userInfoRepository;
        private readonly IBaseReposiotry<UserRoles>  baseReposiotry;
        private readonly IMapper mapper;
        private readonly ILogger<InserUserInfoHandler> logger;

        public InserUserInfoHandler(IBaseReposiotry<UserInfo> userInfoRepository, IMapper mapper, ILogger<InserUserInfoHandler> logger, IBaseReposiotry<UserRoles> baseReposiotry)
        {
            _userInfoRepository = userInfoRepository;
            this.mapper = mapper;
            this.logger = logger;
            this.baseReposiotry = baseReposiotry;

        }

        public async Task<ApiResult> Handle(InserUserInfoRepsultDto request, CancellationToken cancellationToken)
        {
            using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    var user = mapper.Map<UserInfo>(request);
                    await _userInfoRepository.InsetAsync(user);

                    string[] stringids = request.RoleId.Split(',');
                    int[] IntIds = stringids.Select(x => int.Parse(x)).ToArray();
                   var userRoleList = new List<UserRoles>();
                    foreach (var id in IntIds)
                    {
                        userRoleList.Add(new UserRoles()
                        {
                            UserInfoId = user.UserInfoId,
                            RolesId = id
                        });
                    }

                    await baseReposiotry.InsertRangeEntity(userRoleList);
                    tran.Complete();
                    return ApiResult.Ok();
                }
                finally
                {
                    tran.Dispose();
                }
            }
        }
    }
}

public class InserUserInfoRepsultDto : IRequest<ApiResult>
{
    /// <summary>
    /// 用户名
    /// </summary>
    public string UserName { get; set; }
    /// <summary>
    /// 密码
    /// </summary>
    public string Password { get; set; }
    /// <summary>
    /// 角色ID
    /// </summary>
    public string RoleId { get; set; }
}
